package tools;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileExistsException;
import web.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class UpdateServlet extends BaseServlet {
    public void imgUptest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("imgUptest 被访问");
        if(ServletFileUpload.isMultipartContent(req)) {

            // 创建 FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于 解析 上传数据 的工具类 ServletFileUpload 类
            ServletFileUpload servletFileUpload1 = new ServletFileUpload(fileItemFactory);

            try {
                // 解析上传的数据，得到每一个表单项的
                List<FileItem> list = servletFileUpload1.parseRequest(req);
                String userNum = "none";
                // 循环判断
                for(FileItem fileItem : list) {
                    if(fileItem.isFormField()) {
                        // 普通表单项
                        System.out.println("表单name: " + fileItem.getFieldName());   // 表单name属性
                        // 参数 "UTF-8"
                        System.out.println("表单value: " + fileItem.getString("UTF-8"));
                        // 获得账号
                        userNum = fileItem.getString("UTF-8");
                    } else {
                        // 文件
                        System.out.println("--文件--");
                        System.out.println("表单name: " + fileItem.getFieldName());
                        System.out.println("文件value: " + fileItem.getName());    //上传的文件名

                        File img = new File("/webdemo2/web/static/img/userPho/Pho" + userNum + ".jpg");
                        if(img.exists())    img.delete();       // 存在先删除
                        fileItem.write(img);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}
